$(function(){

    if(!window.base.getLocalStorage('token')){
        window.location.href = 'login.html';
    }

    var pageIndex = 1,
        pageSize = 15,
        moreDataFlag=true;

    var menuArr = [
        $('#order-menu'),
        $('#product-menu'),
        $('#category-menu')
    ];

    var moduleArr = [
        $('#order-list'),
        $('#order-detail'),
        $('#product-list'),
        $('#product-detail'),
        $('#category-list'),
        $('#category-detail')
    ];

    var url = {
        orderList: function() {
            return 'order/list';
        },
        productList: function() {
            return 'product/list';
        },
        categoryList: function(){
            return 'category/all';
        },
        orderDetail: function(orderId) {
            return 'order/' + orderId;
        },
        productDetail: function(productId) {
            return 'product/' + productId;
        },
        categoryDetail: function(categoryId) {
            return 'category/' + categoryId;
        }
    };

    init();
    selectMenu($('#order-menu'));
    showOrderList();

    function init() {
        pageIndex=1,
        moreDataFlag=true;
        $('#order-table').children().remove();
        $('#product-table').children().remove();
        $('#category-table').children().remove();
        $('#simple-order').children().remove();
        $('#order-product').children().remove();
        $('.load-more').show().next().hide();
    }

    /**
     * 选择点击的菜单, 切换颜色
     * @param {Object} menu 
     */
    function selectMenu(menu) {
        for (let i = 0; i < menuArr.length; i++) {
            if (menuArr[i] != menu) {
                menuArr[i].find('span').css('color', '#000000')
            }
        }
        menu.find('span').css('color', '#3D6BA4');
    }

    /**
     * 点击菜单(订单管理, 商品管理, 分类管理)
     */
    $('#desktop-menu').find('li').on('click', function() {
        init();
        selectMenu($(this));
        let currentId = $(this).attr('id');
        if (currentId == 'order-menu') {
            showOrderList();
        }
        if (currentId == 'product-menu') {
            showProductList();
        }
        if (currentId == 'category-menu') {
            showCategoryList();
        }
    });

    function showOrderList() {
        showSomeone($('#order-list'));
        getOrders(pageIndex);
    }

    function showOrderDetail($td) {
        showSomeone($('#order-detail'));
        let orderId = $td.attr('data-id');
        getOrderDetail(orderId);
    }

    function showProductList() {
        showSomeone($('#product-list'));
        getProducts(pageIndex);
    }

    function showProductDetail() {
        showSomeone($('#product-detail'));
        //TODO getProductDetail();
    }

    function showCategoryList() {
        showSomeone($('#category-list'));
        getCategories();
    }

    function showCategoryDetail() {
        showSomeone($('#category-detail'));
        //TODO getCategoryDetail();
    }

    function showSomeone(one) {
        for (let i = 0; i < moduleArr.length; i++) {
            if(moduleArr[i] != one) {
                moduleArr[i].hide();
            }
        }
        one.show();
    }

    function getOrderDetail(orderId) {
        let params = {
            url: url.orderDetail(orderId),
            type: 'GET',
            data: {},
            tokenFlag: true,
            sCallback: function(res) {
                let order = res;
                if (order) {
                    let [simpleOrderStr, productsStr] = ['', ''];
                    simpleOrderStr +=
                    '<div><strong>下单时间:</strong><span>' + window.base.dateFormat(new Date(order.createTime)) + '</span></div>' +
                    '<div><strong>订单编号:</strong><span>' + order.orderNo + '</span></div>' +
                    '<div><strong>总&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp价:</strong><span>' + '￥' + order.totalPrice + '</span></div>' +
                    '<div><strong>订单状态:</strong>' + getOrderStatus(order.status) + '</div>';
                    for (let i = 0; i < order.items.length; i++) {
                        let product = order.items[i];
                        productsStr +=
                        '<tr>' +
                        '<td><img width="96px" height="96px" src="' + product.mainImgUrl + '"></td>' +
                        '<td>' + product.name + '</td>' +
                        '<td>￥' + product.price + '</td>' +
                        '<td>' + product.count + '</td>' +
                        '<td>￥' + product.totalPrice + '</td>' +
                        '</tr>';
                    }
                    $('#simple-order').append(simpleOrderStr);
                    $('#order-product').append(productsStr);
                }
            }
        };
        window.base.getData(params);
    }

    /*查看订单*/
    $('#order-table').on('click', '[name=order-no]', function() {
        showOrderDetail($(this));
    });

    /** 查看商品 */
    $('#product-table').on('click', '[name=product-img]', function() {
        //TODO
        showProductDetail();
    });

    /** 查看分类 */
    $('#category-table').on('click', '[name=category-img]', function() {
        //TODO
        showCategoryDetail();
    });

    /** 删除商品 */
    $('#product-table').on('click', '[name=product-delete]', function() {
        let $tr = $(this).parent().parent(),
            productId = $tr.attr('data-id'),
            $tips=$('.global-tips'),
            $p=$tips.find('p');
        let params = {
            url: url.productDetail(productId),
            type: 'DELETE',
            data: {},
            tokenFlag: true,
            sCallback:function(res) {
                if(res.success){
                    $tr.remove();
                    $p.text('操作成功');
                }else{
                    $p.text('操作失败');
                }
                $tips.show().delay(1500).hide(0);
            },
            eCallback:function(){
                $p.text('操作失败');
                $tips.show().delay(1500).hide(0);
            }
        };
        window.base.getData(params);
    });

    /*
    * 获取订单列表数据 分页
    * params:
    * pageIndex - {int} 分页下表  1开始
    */
    function getOrders(pageIndex){
        var params={
            url: url.orderList(),
            data:{
                page:pageIndex,
                size:pageSize
            },
            tokenFlag:true,
            sCallback:function(res) {
                var str = getOrdersHtmlStr(res);
                $('#order-table').append(str);
            }
        };
        window.base.getData(params);
    }

    /**
     * 分页获取商品列表
     * @param {int} pageIndex 
     */
    function getProducts(pageIndex) {
        var params = {
            url: url.productList(),
            data: {
                page: pageIndex,
                size: pageSize
            },
            tokenFlag: false,
            sCallback: function(res) {
                var str = getProductsHtmlStr(res);
                $('#product-table').append(str);
            }
        };
        window.base.getData(params);
    }

    /**
     * 获取分类列表
     */
    function getCategories() {
        let params = {
            url: url.categoryList(),
            data: {},
            tokenFlag: false,
            sCallback: function(res) {
                let str = getCategoriesHtmlStr(res);
                $('#category-table').append(str);
            }
        };
        window.base.getData(params);
    }

    /*拼接订单列表html字符串*/
    function getOrdersHtmlStr(res){
        var data = res.data;
        if (data){
            var len = data.length,
                str = '', item;
            if(len>0) {
                for (var i = 0; i < len; i++) {
                    item = data[i];
                    str += '<tr>' +
                        '<td style="cursor:pointer" name="order-no" data-id="' + item.id + '">' + item.orderNo + '</td>' +
                        '<td>' + item.snapName + '</td>' +
                        '<td>' + item.totalCount + '</td>' +
                        '<td>￥' + item.totalPrice + '</td>' +
                        '<td>' + getOrderStatus(item.status) + '</td>' +
                        '<td>' + window.base.dateFormat(new Date(item.createTime)) + '</td>' +
                        '<td data-id="' + item.id + '">' +
                        getBtns(item.status) + '</td>' +
                        '</tr>';
                }
            } else {
                ctrlLoadMoreBtn();
                moreDataFlag=false;
            }
            return str;
        }
        return '';
    }

    /** 拼接商品列表html字符串 */
    function getProductsHtmlStr(res) {
        let data = res.data;
        if (data) {
            let len = data.length, str = '', product;
            if (len > 0) {
                for (let i = 0; i < len; i++) {
                    product = data[i];
                    str += '<tr data-id="' + product.id + '">' +
                    '<td style="cursor:pointer" name="product-img"><img width="96px" height="96px" src="' +
                    product.mainImgUrl + '"/></td>' +
                    '<td>' + product.name + '</td>' +
                    '<td>￥' + product.price + '</td>' +
                    '<td>' + product.stock + '</td>' +
                    '<td>' + (product.summary || '') + '</td>' +
                    '<td>' + window.base.dateFormat(new Date(product.createTime)) + '</td>' +
                    '<td><span name="product-delete" class="order-btn unstock">删除</span></td>'
                }
            } else {
                ctrlLoadMoreBtn();
                moreDataFlag=false;
            }
            return str;
        }
        return '';
    }

    /** 拼接分类列表html字符串 */
    function getCategoriesHtmlStr(res) {
        let data = res;
        if (data) {
            let len = data.length, str = '', category;
            if (len > 0) {
                for (let i = 0; i < len; i++) {
                    category = data[i];
                    str += '<tr data-id="' + category.id + '">' +
                    '<td style="cursor:pointer" name="category-img"><img width="30%" height="30%" src="' +
                    category.topicImage.url + '"/></td>' +
                    '<td>' + category.name + '</td>' +
                    '<td>' + (category.description || '') + '</td>' +
                    '<td><span name="category-delete" class="order-btn unstock">删除</span></td>'
                }
            } else {
                ctrlLoadMoreBtn();
                moreDataFlag=false;
            }
            return str;
        }
        return '';
    }

    /*根据订单状态获得标志*/
    function getOrderStatus(status){
        var arr=[{
            cName:'unpay',
            txt:'未付款'
        },{
            cName:'payed',
            txt:'已付款'
        },{
            cName:'done',
            txt:'已发货'
        },{
            cName:'unstock',
            txt:'缺货'
        }];
        return '<span class="order-status-txt '+arr[status-1].cName+'">'+arr[status-1].txt+'</span>';
    }

    /*根据订单状态获得 操作按钮*/
    function getBtns(status){
        var arr=[{
            cName:'done',
            txt:'发货'
        },{
            cName:'unstock',
            txt:'缺货'
        }];
        if(status==2 || status==4){
            var index=0;
            if(status==4){
                index=1;
            }
            return '<span class="order-btn '+arr[index].cName+'">'+arr[index].txt+'</span>';
        }else{
            return '';
        }
    }

    /*控制加载更多按钮的显示*/
    function ctrlLoadMoreBtn(){
        if(moreDataFlag) {
            $('.load-more').hide().next().show();
        }
    }

    /*加载更多*/
    $('.load-more').on('click',function(){
        if(moreDataFlag) {
            pageIndex++;
            let parentId = $(this).parent().attr('id');
            if (parentId == 'order-list') {
                getOrders(pageIndex);
            }
            if (parentId == 'product-list') {
                getProducts(pageIndex);
            }
        }
    });

    /*发货*/
    $(document).on('click','.order-btn.done',function(){
        var $this=$(this),
            $td=$this.closest('td'),
            $tr=$this.closest('tr'),
            id=$td.attr('data-id'),
            $tips=$('.global-tips'),
            $p=$tips.find('p');
        var params={
            url:'order/delivery/' + id,
            type:'put',
            data: {},
            tokenFlag:true,
            sCallback:function(res) {
                if(res.success){
                   $tr.find('.order-status-txt')
                       .removeClass('pay').addClass('done')
                       .text('已发货');
                    $this.remove();
                    $p.text('操作成功');
                }else{
                    $p.text('操作失败');
                }
                $tips.show().delay(1500).hide(0);
            },
            eCallback:function(){
                $p.text('操作失败');
                $tips.show().delay(1500).hide(0);
            }
        };
        window.base.getData(params);
    });

    /*退出*/
    $(document).on('click','#login-out',function(){
        window.base.deleteLocalStorage('token');
        window.location.href = 'login.html';
    });
});